<template>
  <div class="root-dependency-panel">
    <el-card class="panel-card" v-loading="isLoading">
      <template #header>
        <div class="panel-header">
          <h3>🔗 根文件依赖详情</h3>
          <p class="panel-description">
            显示各包中引用项目根目录 src 文件的详细信息
          </p>
          <div class="header-stats" v-if="analysisData">
            <el-tag type="danger" size="small">
              总计: {{ analysisData.statistics.rootFileReferences }} 个根文件引用
            </el-tag>
          </div>
        </div>
      </template>

      <!-- 无数据状态 -->
      <div v-if="!analysisData" class="no-data">
        <el-empty description="暂无分析数据" />
      </div>

      <!-- 无根文件引用 -->
      <div v-else-if="packagesWithRootRefs.length === 0" class="no-root-refs">
        <el-result
          icon="success"
          title="太棒了！"
          sub-title="没有发现任何包引用根目录文件，项目结构很规范"
        />
      </div>

      <!-- 根文件引用详情 -->
      <div v-else class="root-refs-content">
        <!-- 概览统计 -->
        <div class="overview-stats">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-tooltip
                effect="dark"
                content="违规包数量：指在项目中有包直接引用了根目录 src 下文件的包数量。这种引用方式破坏了模块化架构，应该避免。"
                placement="top"
              >
                <div class="stat-item">
                  <div class="stat-number">{{ packagesWithRootRefs.length }}</div>
                  <div class="stat-label">违规包数量</div>
                </div>
              </el-tooltip>
            </el-col>
            <el-col :span="8">
              <el-tooltip
                effect="dark"
                content="总引用次数：所有包中对根目录文件的引用总数。包括重复引用同一个文件的情况。数量越大说明架构问题越严重。"
                placement="top"
              >
                <div class="stat-item">
                  <div class="stat-number">{{ totalRootReferences }}</div>
                  <div class="stat-label">总引用次数</div>
                </div>
              </el-tooltip>
            </el-col>
            <el-col :span="8">
              <el-tooltip
                effect="dark"
                content="被引用文件数：根目录中被其他包引用的唯一文件数量。这些文件可能需要重新组织或抽取为独立的共享模块。"
                placement="top"
              >
                <div class="stat-item">
                  <div class="stat-number">{{ uniqueRootFiles.length }}</div>
                  <div class="stat-label">被引用文件数</div>
                </div>
              </el-tooltip>
            </el-col>
          </el-row>
        </div>

        <!-- 按包展示根文件引用 -->
        <div class="packages-section">
          <el-collapse v-model="activePackages">
            <el-collapse-item
              v-for="pkg in packagesWithRootRefs"
              :key="pkg.name"
              :name="pkg.name"
              class="package-collapse-item"
            >
              <template #title>
                <div class="package-header">
                  <div class="package-info">
                    <el-tag type="warning" size="small">📦</el-tag>
                    <span class="package-name">{{ pkg.name }}</span>
                    <el-tag type="danger" size="small" round>
                      {{ pkg.rootFileReferences }} 个引用
                    </el-tag>
                  </div>
                </div>
              </template>

              <div class="package-details">
                <!-- 包基本信息 -->
                <div class="package-info-card">
                  <el-descriptions :column="2" size="small" border>
                    <el-descriptions-item label="包类型">
                      <el-tooltip
                        effect="dark"
                        :content="pkg.type === 'workspace' ? 'Workspace包：通过 monorepo 工具管理的独立包，应该有明确的边界和职责' : '根包：项目的主包，通常包含主要的应用逻辑'"
                        placement="top"
                      >
                        <el-tag :type="pkg.type === 'workspace' ? 'primary' : 'success'" size="small">
                          {{ pkg.type === 'workspace' ? 'Workspace包' : '根包' }}
                        </el-tag>
                      </el-tooltip>
                    </el-descriptions-item>
                    <el-descriptions-item label="包路径">
                      <el-tooltip
                        effect="dark"
                        :content="`完整路径: ${pkg.path}`"
                        placement="top"
                      >
                        <code class="path-code">{{ simplifyFilePath(pkg.path, analysisData?.projectPath) }}</code>
                      </el-tooltip>
                    </el-descriptions-item>
                    <el-descriptions-item label="文件总数">
                      <el-tooltip
                        effect="dark"
                        content="该包中包含的所有源代码文件数量，包括 .ts, .tsx, .js, .jsx, .vue 等文件"
                        placement="top"
                      >
                        <span>{{ pkg.files.length }} 个</span>
                      </el-tooltip>
                    </el-descriptions-item>
                    <el-descriptions-item label="根引用数">
                      <el-tooltip
                        effect="dark"
                        content="该包中对项目根目录 src 文件的引用次数。理想情况下应该为 0，表示包有良好的边界隔离"
                        placement="top"
                      >
                        <el-tag type="danger" size="small">{{ pkg.rootFileReferences }} 个</el-tag>
                      </el-tooltip>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 根文件引用详情表格 -->
                <div class="root-refs-table">
                  <h4>🔍 根文件引用详情</h4>
                  <el-table
                    :data="getRootDependenciesForPackage(pkg)"
                    stripe
                    size="small"
                    :max-height="400"
                  >
                    <el-table-column prop="sourceFile" width="200">
                      <template #header>
                        <el-tooltip
                          effect="dark"
                          content="源文件：当前包中发起引用的文件路径。这些文件违规引用了根目录的文件"
                          placement="top"
                        >
                          <span class="table-header-with-tooltip">源文件</span>
                        </el-tooltip>
                      </template>
                      <template #default="{ row }">
                        <div class="file-info">
                          <el-tag
                            :type="getFileTypeColor(row.sourceFileType)"
                            size="small"
                            class="file-type-tag"
                          >
                            {{ row.sourceFileType.toUpperCase() }}
                          </el-tag>
                          <el-tooltip effect="dark" :content="getFullSourceFilePath(pkg, row)" placement="top">
                            <code class="file-path">{{ row.sourceFile }}</code>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column prop="targetFile" min-width="250">
                      <template #header>
                        <el-tooltip
                          effect="dark"
                          content="引用的根文件：被引用的根目录 src 下的文件路径。这些文件可能需要重构为共享模块"
                          placement="top"
                        >
                          <span class="table-header-with-tooltip">引用的根文件</span>
                        </el-tooltip>
                      </template>
                      <template #default="{ row }">
                        <div class="target-file">
                          <el-icon class="target-icon"><Document /></el-icon>
                          <el-tooltip effect="dark" :content="getFullTargetFilePath(pkg, row)" placement="top">
                            <code class="target-path">{{ row.targetFile }}</code>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column prop="importName" width="150">
                      <template #header>
                        <el-tooltip
                          effect="dark"
                          content="导入内容：从目标文件中导入的具体变量、函数、组件等名称"
                          placement="top"
                        >
                          <span class="table-header-with-tooltip">导入内容</span>
                        </el-tooltip>
                      </template>
                      <template #default="{ row }">
                        <el-tag
                          v-if="row.importName"
                          type="info"
                          size="small"
                          class="import-tag"
                        >
                          {{ row.importName }}
                        </el-tag>
                        <span v-else class="no-import">-</span>
                      </template>
                    </el-table-column>

                    <el-table-column prop="isDynamic" width="100">
                      <template #header>
                        <el-tooltip
                          effect="dark"
                          content="导入类型：静态导入在编译时确定，动态导入在运行时按需加载。动态导入更难追踪和优化"
                          placement="top"
                        >
                          <span class="table-header-with-tooltip">导入类型</span>
                        </el-tooltip>
                      </template>
                      <template #default="{ row }">
                        <el-tag
                          :type="row.isDynamic ? 'warning' : 'success'"
                          size="small"
                        >
                          {{ row.isDynamic ? '动态' : '静态' }}
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

        <!-- 被引用的根文件统计 -->
        <div class="root-files-section">
          <h4>📊 被引用的根文件统计</h4>
          <el-table :data="rootFileStats" stripe size="small" :max-height="300">
            <el-table-column prop="filePath" min-width="250">
              <template #header>
                <el-tooltip
                  effect="dark"
                  content="根文件路径：被其他包引用的根目录文件路径。这些文件建议抽取为独立的共享模块"
                  placement="top"
                >
                  <span class="table-header-with-tooltip">根文件路径</span>
                </el-tooltip>
              </template>
              <template #default="{ row }">
                <div class="root-file-info">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <el-tooltip effect="dark" :content="getFullRootFilePath(row)" placement="top">
                    <code class="root-file-path">{{ row.filePath }}</code>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="referenceCount" width="120">
              <template #header>
                <el-tooltip
                  effect="dark"
                  content="被引用次数：该文件被其他包引用的总次数。次数越多说明该文件越需要被重构为共享模块"
                  placement="top"
                >
                  <span class="table-header-with-tooltip">被引用次数</span>
                </el-tooltip>
              </template>
              <template #default="{ row }">
                <el-tag type="danger" size="small">{{ row.referenceCount }} 次</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="referencingPackages" min-width="200">
              <template #header>
                <el-tooltip
                  effect="dark"
                  content="引用的包：所有引用该文件的包名列表。了解哪些包在使用该文件有助于重构决策"
                  placement="top"
                >
                  <span class="table-header-with-tooltip">引用的包</span>
                </el-tooltip>
              </template>
              <template #default="{ row }">
                <el-tag
                  v-for="pkg in row.referencingPackages"
                  :key="pkg"
                  type="warning"
                  size="small"
                  class="package-tag"
                >
                  {{ pkg }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { Document } from '@element-plus/icons-vue';
import type { IProjectAnalysis, IPackageAnalysis } from '../types/analysis';
import { useAnalysisStore } from '../stores/analysis-store';
import { AnalysisDataService } from '../services/analysis-data';

// 数据服务实例
const analysisDataService = AnalysisDataService.getInstance();

// 响应式数据
const isLoading = ref<boolean>(false);
const analysisData = ref<IProjectAnalysis | null>(null);
const activePackages = ref<string[]>([]);

// 使用全局状态管理
const { currentFilePath, dataVersion } = useAnalysisStore();

/**
 * 根文件引用详情接口
 */
interface IRootDependencyDetail {
  sourceFile: string;
  sourceFileType: string;
  targetFile: string;
  importName: string;
  isDynamic: boolean;
}

/**
 * 根文件统计接口
 */
interface IRootFileStat {
  filePath: string;        // 简化显示的路径
  fullPath: string;        // 完整路径
  referenceCount: number;
  referencingPackages: string[];
}

/**
 * 包含根文件引用的包列表
 */
const packagesWithRootRefs = computed<IPackageAnalysis[]>(() => {
  if (!analysisData.value) return [];
  return analysisData.value.packages.filter(pkg => pkg.rootFileReferences > 0);
});

/**
 * 总的根文件引用数
 */
const totalRootReferences = computed<number>(() => {
  return packagesWithRootRefs.value.reduce((total, pkg) => total + pkg.rootFileReferences, 0);
});

/**
 * 所有被引用的根文件列表（去重）
 */
const uniqueRootFiles = computed<string[]>(() => {
  if (!analysisData.value) return [];

  const rootFiles = new Set<string>();

  packagesWithRootRefs.value.forEach(pkg => {
    pkg.files.forEach(file => {
      file.dependencies
        .filter(dep => dep.type === 'root')
        .forEach(dep => rootFiles.add(dep.path));
    });
  });

  return Array.from(rootFiles);
});

/**
 * 根文件统计信息
 */
const rootFileStats = computed<IRootFileStat[]>(() => {
  if (!analysisData.value) return [];

  const stats = new Map<string, IRootFileStat>();
  const projectPath = analysisData.value.projectPath;

  packagesWithRootRefs.value.forEach(pkg => {
    pkg.files.forEach(file => {
      file.dependencies
        .filter(dep => dep.type === 'root')
        .forEach(dep => {
          const existing = stats.get(dep.path);
          if (existing) {
            existing.referenceCount++;
            if (!existing.referencingPackages.includes(pkg.name)) {
              existing.referencingPackages.push(pkg.name);
            }
          } else {
            stats.set(dep.path, {
              filePath: simplifyFilePath(dep.path, projectPath),
              fullPath: dep.path,
              referenceCount: 1,
              referencingPackages: [pkg.name]
            });
          }
        });
    });
  });

  return Array.from(stats.values()).sort((a, b) => b.referenceCount - a.referenceCount);
});

/**
 * 简化文件路径显示
 * @param filePath - 完整文件路径
 * @param projectPath - 项目根路径
 * @returns 简化后的路径
 */
const simplifyFilePath = (filePath: string, projectPath?: string): string => {
  if (!filePath) return '';

  // 如果有项目路径，先去除项目根路径
  if (projectPath && filePath.startsWith(projectPath)) {
    let relativePath = filePath.substring(projectPath.length);
    // 去除开头的路径分隔符
    if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
      relativePath = relativePath.substring(1);
    }
    return relativePath;
  }

  // 尝试提取相对路径的关键部分
  const pathParts = filePath.replace(/\\/g, '/').split('/');

  // 如果路径包含 src，从 src 开始显示
  const srcIndex = pathParts.findIndex(part => part === 'src');
  if (srcIndex !== -1 && srcIndex < pathParts.length - 1) {
    return pathParts.slice(srcIndex).join('/');
  }

  // 如果路径包含 packages，从包名开始显示
  const packagesIndex = pathParts.findIndex(part => part === 'packages');
  if (packagesIndex !== -1 && packagesIndex < pathParts.length - 2) {
    return pathParts.slice(packagesIndex + 1).join('/');
  }

  // 如果路径太长，只显示最后几级
  if (pathParts.length > 3) {
    return '.../' + pathParts.slice(-3).join('/');
  }

  return filePath;
};

/**
 * 获取指定包的所有根文件依赖详情
 */
const getRootDependenciesForPackage = (pkg: IPackageAnalysis): IRootDependencyDetail[] => {
  const rootDeps: IRootDependencyDetail[] = [];
  const projectPath = analysisData.value?.projectPath;

  pkg.files.forEach(file => {
    file.dependencies
      .filter(dep => dep.type === 'root')
      .forEach(dep => {
        rootDeps.push({
          sourceFile: simplifyFilePath(file.filePath, projectPath),
          sourceFileType: file.fileType,
          targetFile: simplifyFilePath(dep.path, projectPath),
          importName: dep.imports?.join(', ') || dep.name,
          isDynamic: dep.isDynamic
        });
      });
  });

  return rootDeps;
};

/**
 * 获取文件类型对应的颜色
 */
const getFileTypeColor = (fileType: string): string => {
  const colors = {
    vue: 'success',
    ts: 'primary',
    tsx: 'warning',
    js: 'info',
    jsx: 'danger'
  };
  return colors[fileType as keyof typeof colors] || 'default';
};

/**
 * 获取源文件的完整路径（用于工具提示）
 */
const getFullSourceFilePath = (pkg: IPackageAnalysis, row: IRootDependencyDetail): string => {
  // 从包的文件列表中找到匹配的文件
  const matchingFile = pkg.files.find(file =>
    simplifyFilePath(file.filePath, analysisData.value?.projectPath) === row.sourceFile
  );
  return matchingFile?.filePath || row.sourceFile;
};

/**
 * 获取目标文件的完整路径（用于工具提示）
 */
const getFullTargetFilePath = (pkg: IPackageAnalysis, row: IRootDependencyDetail): string => {
  // 从包的文件依赖中找到匹配的依赖
  const matchingDep = pkg.files
    .flatMap(file => file.dependencies)
    .find(dep =>
      dep.type === 'root' &&
      simplifyFilePath(dep.path, analysisData.value?.projectPath) === row.targetFile
    );
  return matchingDep?.path || row.targetFile;
};

/**
 * 获取根文件的完整路径（用于工具提示）
 */
const getFullRootFilePath = (row: IRootFileStat): string => {
  return row.fullPath || row.filePath;
};

/**
 * 加载分析数据
 */
const loadAnalysisData = async (): Promise<void> => {
  try {
    isLoading.value = true;
    console.log('🔄 加载根文件依赖分析数据...');

    analysisData.value = await analysisDataService.loadAnalysisData(currentFilePath.value);

    // 如果有根文件引用，默认展开第一个包
    if (packagesWithRootRefs.value.length > 0) {
      activePackages.value = [packagesWithRootRefs.value[0].name];
    }

    console.log('✅ 根文件依赖分析数据加载完成', {
      packagesWithRootRefs: packagesWithRootRefs.value.length,
      totalRootReferences: totalRootReferences.value,
      uniqueRootFiles: uniqueRootFiles.value.length
    });
  } catch (error) {
    console.error('❌ 加载根文件依赖分析数据失败:', error);
    analysisData.value = null;
  } finally {
    isLoading.value = false;
  }
};

/**
 * 重新加载数据
 */
const reload = (): void => {
  console.log('🔄 重新加载根文件依赖分析数据');
  loadAnalysisData();
};

// 暴露方法供父组件调用
defineExpose({
  reload
});

// 监听数据版本变化，自动重新加载数据
watch(dataVersion, () => {
  console.log('🔄 检测到数据版本变化，重新加载根文件依赖数据');
  loadAnalysisData();
});

// 组件挂载时加载数据
onMounted(() => {
  loadAnalysisData();
});
</script>

<style lang="scss" scoped>
.root-dependency-panel {
  .panel-card {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .panel-header {
    h3 {
      margin: 0 0 8px 0;
      color: #333;
      font-size: 1.2rem;
      font-weight: 600;
    }

    .panel-description {
      margin: 0 0 12px 0;
      color: #666;
      font-size: 0.9rem;
      line-height: 1.4;
    }

    .header-stats {
      margin-top: 8px;
    }
  }

  .no-data,
  .no-root-refs {
    padding: 40px 20px;
    text-align: center;
  }

  .root-refs-content {
    .overview-stats {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;

      .stat-item {
        text-align: center;
        padding: 10px;
        cursor: help;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
          transform: translateY(-2px);
        }

        .stat-number {
          font-size: 2rem;
          font-weight: bold;
          color: #e74c3c;
          line-height: 1;
          margin-bottom: 5px;
        }

        .stat-label {
          font-size: 0.9rem;
          color: #666;
        }
      }
    }

    .packages-section {
      margin-bottom: 30px;

      .package-collapse-item {
        margin-bottom: 12px;
        border: 1px solid #e1e8ed;
        border-radius: 8px;

        .package-header {
          display: flex;
          align-items: center;
          width: 100%;

          .package-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .package-name {
              font-weight: 600;
              color: #333;
            }
          }
        }

        .package-details {
          .package-info-card {
            margin-bottom: 20px;

            .path-code {
              font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
              background: #f8f9fa;
              padding: 2px 6px;
              border-radius: 4px;
              font-size: 0.85rem;
              color: #495057;
            }
          }

          .root-refs-table {
            h4 {
              margin: 0 0 15px 0;
              color: #333;
              font-size: 1rem;
              font-weight: 600;
            }

            .file-info {
              display: flex;
              align-items: center;
              gap: 8px;

              .file-type-tag {
                min-width: 40px;
              }

              .file-path {
                font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                font-size: 0.8rem;
                color: #495057;
                word-break: break-all;
                cursor: help;

                &:hover {
                  color: #007bff;
                  text-decoration: underline;
                }
              }
            }

            .target-file {
              display: flex;
              align-items: center;
              gap: 6px;

              .target-icon {
                color: #409eff;
                flex-shrink: 0;
              }

              .target-path {
                font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                font-size: 0.8rem;
                color: #e74c3c;
                word-break: break-all;
                cursor: help;

                &:hover {
                  color: #dc3545;
                  text-decoration: underline;
                }
              }
            }

            .import-tag {
              font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
              font-size: 0.75rem;
            }

            .no-import {
              color: #999;
              font-style: italic;
            }

            .table-header-with-tooltip {
              cursor: help;
              border-bottom: 1px dashed #409eff;

              &:hover {
                color: #409eff;
              }
            }
          }
        }
      }
    }

    .root-files-section {
      h4 {
        margin: 0 0 15px 0;
        color: #333;
        font-size: 1rem;
        font-weight: 600;
      }

      .root-file-info {
        display: flex;
        align-items: center;
        gap: 6px;

        .file-icon {
          color: #e74c3c;
          flex-shrink: 0;
        }

        .root-file-path {
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
          font-size: 0.8rem;
          color: #e74c3c;
          word-break: break-all;
          cursor: help;

          &:hover {
            color: #dc3545;
            text-decoration: underline;
          }
        }
      }

      .package-tag {
        margin-right: 4px;
        margin-bottom: 2px;
      }

      .table-header-with-tooltip {
        cursor: help;
        border-bottom: 1px dashed #409eff;

        &:hover {
          color: #409eff;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .root-dependency-panel {
    .overview-stats {
      .stat-item {
        padding: 8px;

        .stat-number {
          font-size: 1.5rem;
        }
      }
    }

    .root-refs-table {
      .file-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
      }

      .target-file {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
      }
    }
  }
}
</style>
